package com.wawu.server.dao;

import com.wawu.common.annotation.IOC.component.Repository;
import com.wawu.common.exception.BaseException;
import com.wawu.common.utils.SQLBuilder.SelectSQLBuilder;
import com.wawu.common.utils.SQLBuilder.UpdateSQLBuilder;
import com.wawu.common.utils.SQLExcutorUtil;
import com.wawu.pojo.entity.Good;

import java.sql.SQLException;
import java.util.List;

@Repository
public class GoodsDAO {
    /**
     * 动态条件查询商品列表
     * @param goodQuery
     * @return
     * @throws SQLException
     */
    public List<Good> getGoods(Good goodQuery) throws SQLException {
        SelectSQLBuilder selectSqlBuilder =new SelectSQLBuilder("goods")
                .addDynamicCondition("typeId","=", goodQuery.getTypeId())
                .addDynamicCondition("id","=",goodQuery.getId())
                .addDynamicCondition("name","LIKE", goodQuery.getName())
                .addOrderBy("createtime","DESC");
        return SQLExcutorUtil.queryList(selectSqlBuilder.getSQL(),Good.class, selectSqlBuilder.getParams());
    }
    /**
     * 根据类型动态获取商品基础信息(动态sql)(后续可以作废了，用类封装版)
     * @param typeId
     * @return
     * @throws SQLException
     */
    public List<Good> getGoodsByType(Long typeId) throws SQLException {
        SelectSQLBuilder selectSqlBuilder =new SelectSQLBuilder("goods")
                .addDynamicCondition("typeId","=", typeId)
                .addOrderBy("createtime","DESC");
//        System.out.println(sqlBuilder.getSQL());
        return SQLExcutorUtil.queryList(selectSqlBuilder.getSQL(),Good.class, selectSqlBuilder.getParams());
    }

    //获取商品资料
    public Good getGoodsById(Long id) throws SQLException {
        SelectSQLBuilder sqlBuilder=new SelectSQLBuilder("goods")
                .addDynamicCondition("id","=", id)
                .addOrderBy("createtime","DESC");
        return SQLExcutorUtil.querySingle(sqlBuilder.getSQL(),Good.class,sqlBuilder.getParams());
    }

//    //获取商品描述
//    public String getDescriptionById(Long id) throws SQLException {
//        String sql="SELECT desc FROM goods WHERE id = ? LIMIT 1";
//        return SQLExcutorUtil.queryScalar(sql,String.class,id);
//    }

    //搜索商品
    public List<Good> searchGoods(String keyword) throws SQLException {
        SelectSQLBuilder sqlBuilder=new SelectSQLBuilder("goods")
                .addDynamicCondition("name","LIKE", keyword)
                .addOrderBy("createtime","DESC");
        return SQLExcutorUtil.queryList(sqlBuilder.getSQL(),Good.class,sqlBuilder.getParams());
    }


    //做个测试
    public static void main(String[] args) throws SQLException {
        GoodsDAO goodsDAO =new GoodsDAO();
        List<Good> goodsByType = goodsDAO.getGoodsByType(null);
        System.out.println(goodsByType);

        goodsByType = goodsDAO.getGoodsByType(1L);
        System.out.println(goodsByType);
    }

    //TODO 待优化：此处获取主键如何优化
    /**
     * 插入商品，同时返回主键
     * @param good
     * @return
     */
    public Long insert(Good good) throws SQLException {
        String sql="INSERT INTO `goods` (`name`,`typeId`,`img`,`desc`,`updatetime`,`createtime`) " +
                "VALUES (?,?,?,?,?,?)";//TODO 感觉这里insert操作也是能够封装
        return SQLExcutorUtil.updateAndGetGeneratedKey(sql,good.getName(),good.getTypeId(),good.getImg(),good.getDesc(),good.getUpdatetime(),good.getCreatetime());
    }

    /**
     * 动态更新商品
     * @param good
     */
    public void update(Good good) {
        //先限制整一个异常，后续在搞吧，没啥时间了
        if(good.getId()==null){
            throw new BaseException("商品id为空，无法继续");
        }
        UpdateSQLBuilder updateSQLBuilder=new UpdateSQLBuilder("goods")
                .setField("name",good.getName())
                .setField("typeId",good.getTypeId())
                .setField("img",good.getImg())
                .setField("`desc`",good.getDesc())//TODO 反引号问题
                .setField("updatetime",good.getUpdatetime())
                .addDynamicCondition("id","=",good.getId());//TODO: 待优化：这里不应该整成动态条件的
        //这里异常其实可以先不加的
        try {
            // 调用 SQLExcutorUtil 的 update 方法执行更新
            int rowsAffected = SQLExcutorUtil.update(updateSQLBuilder.getSQL(), updateSQLBuilder.getParams());
            if (rowsAffected == 0) {
                throw new BaseException("更新失败，未找到对应的记录");
            }
        } catch (SQLException e) {
            throw new BaseException("数据库更新操作失败"+e);
        }
    }

    public Integer deleteById(Long goodId) throws SQLException {
        String sql="DELETE FROM `goods` WHERE `id` = ?";
        return SQLExcutorUtil.update(sql,goodId);
    }
}
